package com.linxiao.call.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.linxiao.call.service.ICrmAgentMgrService;
import com.linxiao.call.vo.CrmAgentListResVO;
import com.linxiao.call.vo.CrmAgentParamReqVO;
import com.ruoyi.common.constant.CrmConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.system.domain.SysDeptToken;
import com.ruoyi.system.mapper.SysDeptTokenMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Author qiqi
 * @Date 2023/6/28 14:26
 * @Version 1.0
 */
@Service
public class ICrmAgentMgrServiceImpl implements ICrmAgentMgrService {
    private static final Logger log = LoggerFactory.getLogger(ICrmAgentMgrServiceImpl.class);
    @Value("${tr.call.records.region:null}")
    private String region;
    @Value("${tr.call.records.version:null}")
    private String version;
    @Resource
    private SysDeptTokenMapper sysDeptTokenMapper;

    /**
     * 获取坐席
     *
     * @param crmAgentParamReqVO
     * @return
     */
    @Override
    public List<CrmAgentListResVO> showAgentList(CrmAgentParamReqVO crmAgentParamReqVO) {
        log.info("ICrmAgentMgrServiceImpl.request.param crmAgentParamReqVO={}", JSON.toJSONString(crmAgentParamReqVO));
        if (crmAgentParamReqVO.getMchId() == null) {
            return new ArrayList<>();
        }
        // 1、根据部门ID 获取天润token和企业ID等信息
        SysDeptToken sysDeptToken = new SysDeptToken();
        sysDeptToken.setDeptId(crmAgentParamReqVO.getMchId());
        List<SysDeptToken> sysDeptTokens = sysDeptTokenMapper.selectSysDeptTokenList(sysDeptToken);
        if (StringUtils.isEmpty(sysDeptTokens)) {
            log.info("ICrmAgentMgrServiceImpl.request 根据商户ID未获取到Token信息,mchId={}", crmAgentParamReqVO.getMchId());
            return new ArrayList<>();
        }
        SysDeptToken deptToken = sysDeptTokens.get(0);

        try {
            String webCallURL = this.connectURL(crmAgentParamReqVO, deptToken);
            log.info("webCallURL = {}", webCallURL);
            // 3、远程调用天润接口
            String result = HttpUtil.get(webCallURL);

            //4、返回调用结果
            if (StringUtils.isNotEmpty(result)) {
                JSONObject resObject = JSONObject.parseObject(result);
                // result    Int	0 成功, -1 失败
                if (Objects.nonNull(resObject) && resObject.getIntValue("result") == 0) {
                    JSONObject data = resObject.getJSONObject("data");
                    if (data == null) {
                        return new ArrayList<>();
                    }
                    JSONArray agentStatuses = data.getJSONArray("agentStatuses");
                    TypeReference<List<CrmAgentListResVO>> typeReference = new TypeReference<>() {
                    };
                    List<CrmAgentListResVO> crmAgentListResVOS = JSON.parseObject(agentStatuses.toJSONString(), typeReference);
                    return crmAgentListResVOS;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("ICrmAgentMgrServiceImpl.request 远程调用失败。。。");
        }
        return new ArrayList<>();
    }

    /**
     * 坐席下线
     *
     * @param mchId
     * @param cno
     * @return
     */
    @Override
    public AjaxResult onLine(Long mchId, String cno) {

        // 根据二级部门查询token信息
        SysDeptToken sysDeptToken = new SysDeptToken();
        sysDeptToken.setDeptId(mchId);
        List<SysDeptToken> sysDeptTokens = sysDeptTokenMapper.selectSysDeptTokenList(sysDeptToken);
        JSONObject jsonObject = null;
        try {
            if (Objects.nonNull(sysDeptTokens) && sysDeptTokens.size() > 0) {
                SysDeptToken sysDeptToken1 = sysDeptTokens.get(0);
                String result = getCommonCnoUrl(sysDeptToken1, cno);
                log.info("ICrmAgentMgrServiceImpl.onLine-坐席退出-远程调用接口返回结果 result={},agent={}", result, cno);
                jsonObject = JSONObject.parseObject(result);
                if (jsonObject != null && jsonObject.getIntValue("result") == 0) {
                    return AjaxResult.success(jsonObject.getString("description"));
                }
            }
        } catch (Exception e) {
            log.error("ICrmAgentMgrServiceImpl.onLine.error.exception={}", e);
            return AjaxResult.error("下线异常");
        }
        return AjaxResult.success(jsonObject.getString("description"));
    }

    /**
     * 退出天润坐席
     *
     * @param
     */
    private String getCommonCnoUrl(SysDeptToken sysDeptToken, String cno) {
        // 拼接请求sysDeptToken
        long timestamp = new Date().getTime() / 1000;
        String createCnoURL = String.format(CrmConstants.TR_LOGOUT_CNO_URL, region, version);

        StringBuilder sb = new StringBuilder();
        sb.append("?");
        sb.append("validateType=2");
        sb.append("&enterpriseId=" + sysDeptToken.getEnterpriseId());
        sb.append("&timestamp=" + timestamp);
        sb.append("&cno=" + cno);
        sb.append("&sign=" + Md5Utils.hash(sysDeptToken.getEnterpriseId() + timestamp + sysDeptToken.getTrLoginToken()));
        String url = createCnoURL.concat(sb.toString());
        log.info("cnoUrl = {}", url);
        String recordsResult = HttpUtil.get(url);
        log.info("Execute result[{}]", recordsResult);
        return recordsResult;
    }

    /**
     * 拼接天润语音通知URL
     *
     * @param crmAgentParamReqVO
     * @param deptToken
     * @return
     */
    private String connectURL(CrmAgentParamReqVO crmAgentParamReqVO, SysDeptToken deptToken) {
        long timestamp = new Date().getTime() / 1000;

        String recordUrl = String.format(CrmConstants.TR_AGENT_MOINTER_URL, region, version);
        StringBuilder sb = new StringBuilder();
        sb.append("?");
        sb.append("validateType=2");
        sb.append("&enterpriseId=" + deptToken.getEnterpriseId());
        sb.append("&timestamp=" + timestamp);
        sb.append("&limit=" + 500);
        sb.append("&offset=" + 0);

        if (StringUtils.isNotEmpty(crmAgentParamReqVO.getCnos())) {
            sb.append("&cons=" + crmAgentParamReqVO.getCnos());
        }

        if (StringUtils.isNotEmpty(crmAgentParamReqVO.getStateCode())) {
            sb.append("&stateCode=" + crmAgentParamReqVO.getStateCode());
        }

        sb.append("&sign=" + Md5Utils.hash(deptToken.getEnterpriseId() + timestamp + deptToken.getTrLoginToken()));
        return recordUrl.concat(sb.toString());
    }
}
